<?php

class Admin_PartnerController extends Zend_Controller_Action {

    // Mang tham so nhan duoc o moi Action
    protected $_arrParam;
    protected $_page = 1;
    // Duong dan cua Action chinh
    protected $_actionMain;
    protected $_dir_upload;

    public function init() {
        // Mang tham so nhan duoc o moi Action
        $this->_arrParam = $this->_request->getParams();
        $this->_dir_upload = UPLOAD_PATH . '/images';
        //check permissions
        $auth = Zend_Auth::getInstance();
        $identity = $auth->getIdentity();
        $group_id = $identity->group;
        $groupsModel = new Admin_Model_Groups();
        $group_info = $groupsModel->fetchRow('id=' . $group_id)->toArray();
        $permissions = unserialize($group_info['permissions']);
        if (!$group_info['admin'] || (!in_array($this->_arrParam ['action'], $permissions[ucfirst($this->_arrParam ['controller'])]) && $this->_arrParam ['action'] != 'index')) {
            $this->_redirect('access_denied');
            die();
        }

        $this->_page = $this->_arrParam ['page'];
        if ($this->_page == '' || $this->_page <= 0) {
            $this->_page = 1;
        }

        // Duong dan cua Action chinh
        $this->_actionMain = '/' . $this->_arrParam ['module'] .
                '/' . $this->_arrParam ['controller'] . '/dashboard/page/' . $this->_page;
    }

    /**
     * function Index
     */
    public function indexAction() {
        $this->_redirect($this->_actionMain);
    }

    /**
     * main of users controller
     */
    public function dashboardAction() {
        $translate = Zend_Registry::get('Zend_Translate');
        $this->view->title = $translate->_("TITLE_ADMIN_PARTNER_INDEX");
        $this->view->headTitle($this->view->title);
        $postsModel = new Admin_Model_Posts();
        $list_partners = $postsModel->fetchAll(array('post_type="partner"'));
        $paginator = Zend_Paginator::factory($list_partners);
        $paginator->setItemCountPerPage(NUM_PER_PAGE);
        $paginator->setCurrentPageNumber($this->_page);
        $this->view->page = $this->_page;
        $this->view->paginator = $paginator;
    }

    /**
     * function delete multi location (ajax)
     */
    public function deleteitemsAction() {
        $this->_helper->layout()->disableLayout();
        $postsModel = new Admin_Model_Posts();
        if ($this->_request->isPost()) {
            $item = $this->_arrParam ['cid'];
            foreach ($item as $k => $v) {
                $postsModel->delete(array('id=' . $v));
            }
        }
        $this->_redirect($this->_actionMain);
    }

    /**
     * function change status of use (ajax)
     */
    public function activeAction() {
        $this->_helper->layout()->disableLayout();
        $type = $this->_request->getParam('type', 1);
        $id = $this->_request->getParam('id', 0);

        if ($type > 0) {
            $type = 1;
        } else {
            $type = 0;
        }

        $postsModel = new Admin_Model_Posts();
        $data = array('post_status' => $type);
        $postsModel->updatePost($id, $data);
        $this->_redirect($this->_actionMain);
    }

    /**
     * function insert one user
     */
    public function insertAction() {
        $messages = array();
        $translate = Zend_Registry::get('Zend_Translate');
        $this->view->title = $translate->_("TITLE_ADMIN_PARTNER_INSERT");
        $this->view->headTitle($this->view->title);

        $form = new Admin_Form_Partner_Partner();
        $form->setAttrib('enctype', 'multipart/form-data');
        $back = $form->getElement('back');
        $back->setAttrib('onclick', "window.location='" . $this->getFrontController()->getBaseUrl() . "/admin/partner/dashboard/page/" . $this->_page . "';");

        //kiem tra co phai la post khong
        if ($this->_request->isPost()) {
            if ($form->isValid($_POST)) {
                //khoi tao zend file
                $upload = new Zend_File_Transfer_Adapter_Http();
                $upload->setDestination($this->_dir_upload);
                $upload->addValidator('Count', false, array(
                            'min' => 1,
                            'max' => 1
                        ))
                        ->addValidator('Size', false, array(
                            'min' => 20,
                            'max' => 10485760
                        ))
                        ->addValidator('Extension', false, 'jpg,png,gif');


                $postsModel = new Admin_Model_Posts();
                $auth = Zend_Auth::getInstance();
                $identity = $auth->getIdentity();

                $post_status = $_POST ['post_status'];
                $post_title = trim($form->getValue('post_title'));
                $post_content = trim($form->getValue('post_content'));
                $post_order = trim($form->getValue('post_order'));
                $post_author = $identity->id;
                $post = array(
                    'post_status' => $post_status,
                    'post_title' => $post_title,
                    'post_content' => $post_content,
                    'post_author' => $post_author,
                    'post_order' => (int) $post_order,
                    'post_parent' => 0,
                    'post_type' => 'partner'
                );

                $post_id = $postsModel->insertPost($post);
                $postMetaModel = new Admin_Model_PostsMeta();
                $data_meta_adress = array(
                    'post_id' => $post_id,
                    'meta_key' => 'partner_address',
                    'meta_value' => trim($form->getValue('partner_address'))
                );
                $postMetaModel->insert($data_meta_adress);
                if ($upload->isValid()) {
                    $files = $upload->getFileInfo();
                    foreach ($files as $file => $info) {
                        if ($info['name'] != '') {
                            $validator = new Zend_Validate_File_Exists($this->_dir_upload);
                            if ($validator->isValid($info['name'])) {
                                $file_name = $upload->getFileName($info['name']);
                                preg_match("/\.([^\.]+)$/", $file_name, $matches);
                                $file_ext = $matches[1];
                                $file_name = time() . '.' . $file_ext;
                                $arrFileName[$file] = $file_name;
                                $upload->addFilter('Rename', $this->_dir_upload . '/' . $file_name);
                            } else {
                                $arrFileName[$file] = $info['name'];
                            }
                            $upload->receive($file);
                        }
                    }
                    //EOB: save file to server	 
                    $data_meta_image = array(
                        'post_id' => $post_id,
                        'meta_key' => 'partner_logo',
                        'meta_value' => $arrFileName['partner_logo']
                    );
                    $postMetaModel->insert($data_meta_image);
                }

                $messages [] = array(
                    'text' => $translate->_("TEXT_NOTE_INSERT_PARTNER_SUCCESS"),
                    'type' => 'success'
                );
            }
        }

        $this->view->message = $messages;
        $this->view->form = $form;
    }

    /**
     * function edit info one location by id
     */
    public function updateAction() {
        $translate = Zend_Registry::get('Zend_Translate');
        $this->view->title = $translate->_("TITLE_ADMIN_PARTNER_UPDATE");
        $this->view->headTitle($this->view->title);


        $form = new Admin_Form_Partner_Partner();
        $back = $form->getElement('back');
        $back->setAttrib('onclick', "window.location='" . $this->getFrontController()->getBaseUrl() . "/admin/partner/dashboard/page/" . $this->_page . "';");

        $post_id = $this->_getParam('id', 0);
        $postsModel = new Admin_Model_Posts();
        $postMetaModel = new Admin_Model_PostsMeta();
        $messages = array();

        if ($this->_request->isPost()) {
            if ($form->isValid($_POST)) {

                $upload = new Zend_File_Transfer_Adapter_Http();
                $upload->setDestination($this->_dir_upload);
                $upload->addValidator('Count', false, array(
                            'min' => 1,
                            'max' => 1
                        ))
                        ->addValidator('Size', false, array(
                            'min' => 20,
                            'max' => 10485760
                        ))
                        ->addValidator('Extension', false, 'jpg,png,gif');

                $post_status = $_POST ['post_status'];
                $post_title = trim($form->getValue('post_title'));
                $post_content = trim($form->getValue('post_content'));
                $post_order = trim($form->getValue('post_order'));

                $data = array(
                    'post_status' => $post_status,
                    'post_title' => $post_title,
                    'post_content' => $post_content,
                    'post_order' => (int) $post_order
                );

                $process_upadte = $postsModel->updatePost($post_id, $data);
                $data_meta_adress = array(
                    'meta_value' => trim($form->getValue('partner_address'))
                );
                $postMetaModel->update($data_meta_adress, array('post_id=' . $post_id, 'meta_key="partner_address"'));

                if ($upload->isValid()) {
                    $files = $upload->getFileInfo();
                    foreach ($files as $file => $info) {
                        if ($info['name'] != '') {
                            $validator = new Zend_Validate_File_Exists($this->_dir_upload);
                            if ($validator->isValid($info['name'])) {
                                $file_name = $upload->getFileName($info['name']);
                                preg_match("/\.([^\.]+)$/", $file_name, $matches);
                                $file_ext = $matches[1];
                                $file_name = time() . '.' . $file_ext;
                                $arrFileName[$file] = $file_name;
                                $upload->addFilter('Rename', $this->_dir_upload . '/' . $file_name);
                            } else {
                                $arrFileName[$file] = $info['name'];
                            }
                            $upload->receive($file);
                        }
                    }
                    //EOB: save file to server	 


                    $check_meta_exits = $postMetaModel->fetchRow(array('post_id=' . $post_id, 'meta_key="partner_logo"'));
                    if ($check_meta_exits) {
                        $data_meta_image = array(
                            'meta_value' => $arrFileName['partner_logo']
                        );
                        $postMetaModel->update($data_meta_image, array('post_id=' . $post_id, 'meta_key="partner_logo"'));
                    } else {
                        $data_meta_image = array(
                            'post_id' => $post_id,
                            'meta_key' => 'partner_logo',
                            'meta_value' => $arrFileName['partner_logo']
                        );
                        $postMetaModel->insert($data_meta_image);
                    }
                }

                if ($process_upadte) {
                    $messages [] = array(
                        'text' => $translate->_("TEXT_NOTE_INSERT_UPDATE_SUCCESS"),
                        'type' => 'success'
                    );
                } else {
                    $messages [] = array(
                        'text' => $translate->_("TEXT_NOTE_INSERT_UPDATE_FAILD"),
                        'type' => 'errormsg'
                    );
                }
            }
        } else {
            $data = $postsModel->fetchRow('id=' . $post_id)->toArray();
            $data_meta = $postMetaModel->fetchAll(array('post_id=' . $post_id))->toArray();
            foreach ($data_meta as $meta) {
                $data[$meta['meta_key']] = $meta['meta_value'];
            }
            if (count($data) > 0) {
                $form->populate($data);
            } else {
                $this->_redirect($this->_actionMain);
            }
        }

        $this->view->message = $messages;
        $this->view->form = $form;
    }

    /**
     * function delete one location by id
     */
    public function deleteAction() {
        $translate = Zend_Registry::get('Zend_Translate');
        $this->view->title = $translate->_("TITLE_ADMIN_PARTNER_DELETE");
        $this->view->headTitle($this->view->title);
        $id = $this->_getParam('id', 0);
        $postsModel = new Admin_Model_Posts();
        if ($this->getRequest()->isPost()) {
            $del = $this->getRequest()->getPost('del');
            if ($del == 'Yes') {
                $process = $postsModel->delete(array('id=' . $id));
            }
            $this->_redirect($this->_actionMain);
        } else {
            $post = $postsModel->fetchRow('id=' . $id)->toArray();
            $this->view->post = $post;
        }
    }

}